Popular Searches
Popular Course Categories
Popular Courses

Implementing URL Rewriting and Hidden Form Fields

Implementing URL Rewriting and Hidden Form Fields

Session Management, Cookies, and Servlet Filters

Implementing URL Rewriting and Hidden Form Fields in Advanced Java

Course: Advanced Java Training

Topic: Implementing URL Rewriting and Hidden Form Fields

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Session Tracking

Session tracking is a technique used in Java web applications to maintain information across multiple HTTP requests. HTTP is a stateless protocol, which means that each request is independent unless the application uses a mechanism to associate requests with the same user or interaction.

For example, when a user logs in to a website, the application may need to remember the user's identity while they navigate to different pages. Session tracking techniques help maintain this information between requests.

Common session tracking techniques in Advanced Java include:

  • Cookies
  • HttpSession
  • URL rewriting
  • Hidden form fields

URL rewriting and hidden form fields are useful concepts for understanding session management, especially when studying how information is passed between servlets and web pages.

2. Learning Objectives

  • Understand why session tracking is required in web applications.
  • Learn the meaning and purpose of URL rewriting.
  • Implement URL rewriting using servlet response methods.
  • Understand the purpose of hidden form fields.
  • Pass data between HTML forms and Java Servlets.
  • Compare URL rewriting, hidden fields, cookies, and HttpSession.
  • Understand the limitations and security risks of both techniques.
  • Build a small multi-page application using URL rewriting and hidden form fields.

3. Why Is Session Tracking Required?

HTTP does not automatically remember the information submitted in an earlier request. Consider an online shopping application where a user selects a product and then proceeds to checkout. The application needs a way to carry relevant state from one step to the next.

Without session tracking, each request would need to provide the information required for that particular operation. Session tracking mechanisms make it possible to associate requests or transfer specific values between application steps.

Example Scenario

  1. A user enters their name on a registration page.
  2. The application processes the first request.
  3. The user proceeds to another page.
  4. The application needs the name or another identifier to continue the workflow.
  5. URL rewriting or a hidden form field can carry selected information to the next request.

These mechanisms do not automatically provide authentication, authorization, or secure storage. The application must implement those protections separately.

4. What Is URL Rewriting?

URL rewriting is a session tracking technique in which information is added to a URL so that it can be carried when the browser navigates to another resource.

In servlet applications, URL rewriting may be used to support session tracking when cookies are unavailable or unsuitable. The servlet container can encode the session identifier into a URL, typically as a path parameter.

Example of a Rewritten URL

https://example.com/shop;jsessionid=ABC123XYZ

The value shown above is illustrative. A real session ID is generated and managed by the servlet container. Applications should not manually invent session IDs or expose them unnecessarily.

How URL Rewriting Works

  1. The browser sends a request to a servlet.
  2. The servlet obtains or uses the relevant session.
  3. The application generates a link or redirect to another resource.
  4. The servlet container may encode session-tracking information into the URL.
  5. The browser follows the rewritten URL.
  6. The container uses the session identifier to associate the request with the session, if the session remains valid.

5. URL Rewriting Using encodeURL()

The encodeURL() method of HttpServletResponse prepares a URL for session tracking. Depending on the container's session-tracking configuration and the request, the returned URL may contain session information or remain unchanged.

Syntax

String encodedURL = response.encodeURL(url);

Example: Creating a Rewritten Link

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/home")
public class HomeServlet extends HttpServlet {

    @Override
    protected void doGet(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        session.setAttribute("username", "Amit");

        String dashboardURL =
            response.encodeURL(
                request.getContextPath() + "/dashboard"
            );

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        response.getWriter().println(
            "" +
            "" +
            "" +
            "" +
            "" +
            "

Home Page

" +
            "<a href="" + dashboardURL +
            "">Open Dashboard</a>" +
            ""
        );
    }
}

The servlet creates or retrieves a session and generates a dashboard URL using encodeURL(). The container determines whether session information needs to be included in the URL.

Important: In production code, HTML output should be generated with a template engine or carefully escaped values. Do not concatenate untrusted user input into HTML. The example uses a server-generated URL and a fixed link label for illustration.

6. URL Rewriting with Redirects

When a servlet redirects a browser to another URL, the encodeRedirectURL() method can encode the destination for session tracking. This method is specifically intended for URLs used with sendRedirect().

Example

String dashboardURL =
    request.getContextPath() + "/dashboard";

String encodedRedirectURL =
    response.encodeRedirectURL(dashboardURL);

response.sendRedirect(encodedRedirectURL);

Use encodeURL() when generating ordinary links and encodeRedirectURL() when generating redirect destinations. The servlet container decides whether URL encoding is necessary.

7. Important Methods for URL Rewriting

Method Purpose Typical Use
response.encodeURL(url) Encodes a URL for session tracking when required. HTML links and navigation URLs.
response.encodeRedirectURL(url) Encodes a URL intended for a redirect when required. Before calling sendRedirect().
response.sendRedirect(url) Instructs the browser to navigate to another URL. Redirecting after an operation.
request.getSession() Retrieves an existing session or creates one. When session state is required.
request.getSession(false) Returns an existing session or null without creating one. Checking for existing session state.

8. Advantages of URL Rewriting

  • Can support session tracking when the browser does not accept session cookies.
  • Works with dynamically generated links and redirects when URLs are correctly encoded.
  • Can help preserve session association during navigation between servlet resources.
  • Does not require storing arbitrary application data in every link manually when the container manages session-ID encoding.
  • Helps explain how servlet containers support session tracking across different client configurations.

9. Limitations and Security Risks of URL Rewriting

  • Session identifiers may appear in browser address bars, browser history, server logs, bookmarks, cached content, and referrer information.
  • A leaked session identifier can allow session impersonation if it remains valid.
  • Every relevant generated link and redirect must be encoded correctly for URL-based session tracking.
  • Static pages may not automatically encode URLs in the same way as dynamically generated servlet responses.
  • URLs may be copied or shared, unintentionally exposing session-tracking information.
  • Long URLs may be inconvenient or unsupported in some environments.

Prefer secure cookie-based session tracking when it is appropriate. URL rewriting should be considered carefully because exposing session IDs in URLs creates significant security risks. Never place passwords, access tokens, or other secrets in URLs.

10. What Are Hidden Form Fields?

A hidden form field is an HTML input element with type="hidden". It allows a form to submit a value to the server without displaying a visible input control to the user.

Basic Syntax

<input type="hidden" name="username" value="Amit">

Hidden fields are commonly used to carry a record identifier, a workflow step, or other non-sensitive information from one form submission to another.

Although the input is not visible on the page, its value can be viewed or modified by the user through browser developer tools or a crafted HTTP request. A hidden field is not a secure storage mechanism and must never be trusted as proof of identity or authorization.

11. Creating a Hidden Form Field

To create a hidden field, add an input element with the type attribute set to hidden. The name attribute identifies the submitted parameter, and the value attribute specifies its current value.

HTML Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hidden Field Example</title>
</head>
<body>
    <h1>User Details</h1>

    <form action="process-details" method="post">
        <label for="email">Email Address:</label>
        <input type="email" id="email"
               name="email" required>

        <input type="hidden"
               name="workflowStep"
               value="profile">

        <button type="submit">Continue</button>
    </form>
</body>
</html>

When the form is submitted, the browser sends both the visible email field and the hidden workflowStep field. The hidden field is not shown as a normal input, but it is still part of the submitted request.

12. Retrieving Hidden Fields in a Servlet

Hidden fields are submitted as ordinary form parameters. A servlet retrieves them using request.getParameter(), just as it would retrieve values from text boxes, dropdowns, or other form controls.

Servlet Example

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/process-details")
public class ProcessDetailsServlet extends HttpServlet {

    @Override
    protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String email = request.getParameter("email");
        String workflowStep =
            request.getParameter("workflowStep");

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        response.getWriter().println(
            "Email parameter received: " +
            (email != null && !email.isBlank())
        );

        if ("profile".equals(workflowStep)) {
            response.getWriter().println(
                "Profile workflow step received."
            );
        } else {
            response.getWriter().println(
                "Unexpected workflow step."
            );
        }
    }
}

The servlet reads the hidden field and compares it against an expected value. This check is useful for validating the request format, but a hidden field must not be used as the only control for access permissions or security-sensitive decisions.

13. Passing Data Between Multiple Forms

Hidden form fields can carry non-sensitive information between consecutive form submissions. This approach is useful for multi-step forms where the browser submits one stage and then opens another.

Example: First Form

<form action="step-two" method="post">
    <label for="fullName">Full Name:</label>
    <input type="text" id="fullName"
           name="fullName" required>

    <button type="submit">Next</button>
</form>

Example: Second Form

After validating the first form, a servlet can render a second form and include a previously submitted value as a hidden field. The value must be escaped for the HTML attribute context before being rendered.

<form action="complete-registration" method="post">
    <input type="hidden"
           name="fullName"
           value="Amit Sharma">

    <label for="city">City:</label>
    <input type="text" id="city"
           name="city" required>

    <button type="submit">Complete</button>
</form>

The second form sends the name again with the city field. The fixed name shown in the example is illustrative; in a real application, render the value from server-side data using a template engine that performs appropriate HTML attribute escaping.

14. URL Rewriting vs Hidden Form Fields

Feature URL Rewriting Hidden Form Fields
Where information is carried In a URL, such as a path parameter. In a submitted HTML form parameter.
Navigation support Can support links and redirects when encoded correctly. Works when the form containing the hidden field is submitted.
Requires a form? No. Yes, for normal browser form submission.
Data visibility May be visible in the address bar and related URL records. Not normally visible as a form control, but inspectable and editable by the client.
Data persistence Information is carried only when the rewritten URL is followed. Information is carried only when the form submits the field.
Session tracking The servlet container can encode a session ID into URLs. Can carry selected application values but does not automatically manage an HttpSession.
Security considerations Session IDs in URLs can leak and should be avoided where possible. Values are untrusted client input and can be modified.

15. URL Rewriting vs Cookies

Feature URL Rewriting Cookies
Storage or transport Session information is carried in generated URLs. Browser sends cookie values with matching requests.
Browser configuration Can help when cookies are unavailable, if the application and container support it. Requires the browser to accept and return cookies.
Visibility Session information may appear in URLs. Cookie values are not normally displayed in the address bar.
Navigation Generated links and redirects need correct URL encoding. Cookies are sent automatically for matching requests according to cookie rules.
Security URL exposure is a major concern for session identifiers. Use HTTPS and appropriate Secure, HttpOnly, and SameSite attributes.

16. URL Rewriting vs HttpSession

These techniques serve different roles. HttpSession is the server-side abstraction used to store session attributes, while URL rewriting can be one method for carrying the session identifier between requests.

Feature HttpSession URL Rewriting
Purpose Stores server-side session attributes. Helps associate requests with a session by encoding session information into URLs.
Data storage Session attributes are managed by the server. Typically carries a session identifier in the URL rather than storing arbitrary Java objects.
API getSession(), setAttribute(), getAttribute(). encodeURL() and encodeRedirectURL().
Typical role Maintain user-specific state. Provide an alternative session-tracking path when necessary.

17. Security Considerations for Hidden Form Fields

Hidden fields are useful for carrying data, but they are not a security boundary. A user can change the value before submitting the form, regardless of whether the field is visible.

  • Never store passwords, secret keys, or sensitive tokens in hidden fields without a well-designed security mechanism.
  • Never trust a hidden field to determine whether a user is an administrator.
  • Validate all submitted values on the server.
  • Check authorization against server-side records rather than trusting a submitted user ID.
  • Use CSRF protection for state-changing operations when appropriate.
  • Escape values correctly when placing them into HTML attributes.
  • Use a server-side session or database to store authoritative workflow state when needed.
  • Consider signing or validating tamper-sensitive values when a stateless workflow requires client-carried data; a signature does not provide confidentiality.

18. Security Best Practices for URL Rewriting

  • Prefer cookie-based session tracking over session IDs in URLs when suitable.
  • Use encodeURL() for generated links and encodeRedirectURL() for redirect targets when URL-based session tracking is needed.
  • Never manually append session IDs to URLs.
  • Never include passwords, access tokens, or confidential personal data in URLs.
  • Use HTTPS throughout authenticated workflows.
  • Rotate session identifiers after authentication when appropriate to prevent session fixation.
  • Invalidate sessions on logout.
  • Configure reasonable session inactivity timeouts.
  • Do not log complete URLs containing sensitive query parameters or session identifiers.
  • Verify that protected endpoints perform authentication and authorization checks.

19. Common Errors and Troubleshooting

Problem Possible Cause Solution
Session is lost after clicking a link The URL was not encoded when URL rewriting was required. Use response.encodeURL() for generated links.
Session is lost after redirecting The redirect URL was not encoded when required. Use response.encodeRedirectURL() before sendRedirect().
Hidden field returns null The field name is incorrect, the field was omitted, or the request did not submit the form. Check the input name and form submission method.
Hidden field has an unexpected value The client changed the field or submitted a crafted request. Validate the value and check authoritative server-side state.
URL contains session information The container is using URL rewriting for session tracking. Review tracking configuration and prefer cookies where suitable.
Session ID appears in logs Complete URLs are being logged. Redact sensitive URL components and review logging configuration.
Data is not preserved between form steps The next form does not include the value or the server did not retain the required state. Check the form fields and consider HttpSession or server-side workflow storage.
Unexpected access is granted The application trusts a hidden field or URL parameter for authorization. Enforce authentication and authorization on the server for each protected operation.

20. Practical Project: Multi-Step Registration Form

Create a multi-step registration application to practice URL rewriting and hidden form fields.

Project Requirements

  1. Create a first form that collects a user's full name.
  2. Submit the form to a servlet using POST.
  3. Validate the name and render a second form.
  4. Carry the non-sensitive name value into the second form using a hidden field.
  5. Collect the user's city in the second form.
  6. Validate both values on the server.
  7. Display a confirmation page without exposing unnecessary personal information.
  8. Create a separate navigation link using response.encodeURL().
  9. Demonstrate a redirect using response.encodeRedirectURL().
  10. Test invalid inputs and tampered hidden-field values.

Suggested Project Structure

advanced-java-session-tracking/
├── src/main/java/
│   └── com/example/
│       └── servlet/
│           ├── StepOneServlet.java
│           ├── StepTwoServlet.java
│           └── CompleteRegistrationServlet.java
└── src/main/webapp/
    ├── registration.html
    └── WEB-INF/
        └── web.xml

For a production-quality implementation, prefer storing authoritative workflow data server-side when possible. Treat every submitted field as untrusted, even when it was originally generated by your own application.

21. Interview Questions and Answers

Q1. What is URL rewriting?

URL rewriting is a technique for carrying information in a URL. In servlet applications, it can be used to support session tracking by encoding the session identifier into generated URLs when required.

Q2. Which method is used to encode a normal URL?

response.encodeURL(url) prepares a URL for session tracking when necessary.

Q3. What is the purpose of encodeRedirectURL()?

It prepares a URL intended for sendRedirect() and allows the container to include session-tracking information when required.

Q4. What is a hidden form field?

A hidden form field is an HTML input with type="hidden". It submits a value with a form without displaying a normal input control.

Q5. How does a servlet retrieve a hidden field?

It uses request.getParameter("fieldName"), just like any other form parameter.

Q6. Are hidden fields secure?

No. Users can inspect and modify hidden fields. They must not be trusted for authentication, authorization, or other security-sensitive decisions.

Q7. What is the main disadvantage of URL rewriting?

Session identifiers can be exposed in URLs, logs, browser history, bookmarks, and referrer information, potentially enabling session impersonation.

Q8. Can hidden fields replace HttpSession?

Not completely. Hidden fields carry selected values with a form submission, whereas HttpSession stores server-side attributes across associated requests.

Q9. Why should encodeURL() be used for generated links?

It allows the servlet container to add session-tracking information when needed, helping preserve session association in environments where URL rewriting is used.

Q10. When should URL rewriting be avoided?

Avoid it when secure cookie-based session tracking is available and suitable, especially for authenticated applications where exposing session identifiers in URLs would create unnecessary risk.

Q11. What is the difference between URL rewriting and ordinary URL encoding?

URL rewriting for servlet session tracking may add session-tracking information to a URL. Ordinary URL encoding generally converts characters into a format suitable for URL components. They are different operations.

Q12. What should be done with hidden-field values before database use?

Validate them on the server, enforce authorization using trusted server-side data, and use parameterized database queries such as JDBC PreparedStatement.

22. Quick Revision Checklist

  • HTTP is stateless by default.
  • Session tracking associates related requests or carries selected state between requests.
  • URL rewriting can carry session-tracking information in generated URLs.
  • response.encodeURL() is used for ordinary generated links.
  • response.encodeRedirectURL() is used for redirect destinations.
  • Hidden fields use the HTML input type hidden.
  • Servlets retrieve hidden values through request.getParameter().
  • Hidden fields are client-controlled and are not secure storage.
  • Session IDs in URLs can leak through browser history, logs, and referrer information.
  • Prefer secure cookie-based session tracking where appropriate.
  • Validate every submitted value on the server.
  • Protect state-changing operations and verify authorization independently of submitted values.

23. Conclusion

URL rewriting and hidden form fields are two techniques used to carry information between requests in Java web applications. URL rewriting can support session tracking by encoding session information into generated URLs, while hidden form fields carry selected values when an HTML form is submitted.

Both techniques have limitations and must be implemented carefully. Hidden fields can be modified by users, and URL rewriting can expose session identifiers. For modern applications, prefer secure cookie-based session tracking when suitable, use HttpSession for server-side state, validate every request, and apply appropriate authentication, authorization, and output-encoding practices.

Continue learning through the Advanced Java Training Course, explore the course demo registration page, or visit the JustAcademy official website.

Previous Next
whatsapp